﻿using AuthTemplate.DTO.Common;
using AuthTemplate.DTO.StudentCash;
using AuthTemplate.Entity;
using AuthTemplate.Infrastructure;
using AuthTemplate.Infrastructure.Token;
using AuthTemplate.MVC.Filter;
using AuthTemplate.Service;
using AuthTemplate.ViewModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace AuthTemplate.MVC.Controllers
{
    
    [RoutePrefix("studentCash")]
    public class StudentCashController : BaseController
    {
        private readonly IStudentCashService studentCashService;

        private readonly IStudentInfoService studentInfoService;
        public StudentCashController(IStudentCashService studentCashService,
            IStudentInfoService studentInfoService)
        {
            this.studentCashService = studentCashService;
            this.studentInfoService = studentInfoService;
        }

        [LoginFilter]
        [HttpPost]
        [Route("uploadFile")]
        public string UploadFile(UploadCashInput input)
        {
            MyResponse resp = new MyResponse();
            List<string> paths = new List<string>();
            try
            {
                string token = HttpContext.Request.Headers["Authorization"].Substring(7).Trim();
                string userId = CommonToken.DecodeToken(token, false).UserID;

                #region 接收所有文件

                HttpFileCollectionBase myfiles = Request.Files;
                var filePath = Server.MapPath(string.Format("~/{0}", "CashFile/"+ userId));
                if (!Directory.Exists(filePath))
                {
                    DirectoryInfo di = Directory.CreateDirectory(filePath);
                }
                
                for (int i = 0; i < myfiles.Count; i++)
                {
                    string path = filePath + "/" + myfiles[i].FileName;
                    if(DirFile.IsExistFile(path))
                    {
                        FileOperate.FileDel(path);
                    }
                    myfiles[i].SaveAs(path);
                    paths.Add(path);
                }

                #endregion

                input.userid = userId;
                studentCashService.UploadCash(paths,input);

                #region 删除所有文件

                foreach(string path in paths)
                {
                    if (DirFile.IsExistFile(path))
                    {
                        FileOperate.FileDel(path);
                    }
                }

                #endregion
            }
            catch (Exception ex)
            {
                resp.Code = 500;
                resp.Message = "操作失败" + ex.Message;
            }
            
            return JsonHelper.Serialize(resp);
        }

        [LoginFilter]
        [HttpPost]
        [Route("uploadStudent")]
        public string UploadStudent()
        {
            MyResponse resp = new MyResponse();
            List<string> paths = new List<string>();
            try
            {
                string token = HttpContext.Request.Headers["Authorization"].Substring(7).Trim();
                string userId = CommonToken.DecodeToken(token, false).UserID;

                #region 接收所有文件

                HttpFileCollectionBase myfiles = Request.Files;
                var filePath = Server.MapPath(string.Format("~/{0}", "StudentFile/" + userId));
                if (!Directory.Exists(filePath))
                {
                    DirectoryInfo di = Directory.CreateDirectory(filePath);
                }

                for (int i = 0; i < myfiles.Count; i++)
                {
                    string path = filePath + "/" + myfiles[i].FileName;
                    if (DirFile.IsExistFile(path))
                    {
                        FileOperate.FileDel(path);
                    }
                    myfiles[i].SaveAs(path);
                    paths.Add(path);
                }

                #endregion

                studentInfoService.UploadStudent(paths);

                #region 删除所有文件

                foreach (string path in paths)
                {
                    if (DirFile.IsExistFile(path))
                    {
                        FileOperate.FileDel(path);
                    }
                }

                #endregion
            }
            catch (Exception ex)
            {
                resp.Code = 500;
                resp.Message = "操作失败" + ex.Message;
            }

            return JsonHelper.Serialize(resp);
        }

        [LoginFilter]
        [HttpPost]
        [Route("deleteAllStudentInfo")]
        public string DeleteAllStudentInfo()
        {
            MyResponse resp = new MyResponse();
            try
            {
                studentInfoService.DeleteAllStudentInfo();
            }
            catch (Exception ex)
            {
                resp.Code = 500;
                resp.Message = "操作失败" + ex.Message;
            }
            return JsonHelper.Serialize(resp);
        }

        [LoginFilter]
        [HttpGet]
        [Route("getAllStudentCash")]
        public string GetAllStudentCash(int page, int limit,DateTime startTime , DateTime endTime, string studentNo, string key)
        {
            TableData<List<StudentCash>> resp = new TableData<List<StudentCash>>();
            try
            {
                int count = 0;
                var studentCashs = studentCashService.GetAllStudentCash(page, limit,startTime ,endTime, studentNo, out count);
                resp.data = studentCashs;
                resp.code = 0;
                resp.msg = "操作成功";
                resp.count = count;
            }
            catch (Exception ex)
            {
                resp.code = 500;
                resp.msg = "操作失败" + ex.Message;
                resp.count = 0;
            }
            return JsonHelper.Serialize(resp);
        }

        [LoginFilter]
        [HttpPost]
        [Route("editStudentCash")]
        public string EditStudentCash(StudentCash input)
        {
            MyResponse resp = new MyResponse();
            try
            {
                string token = HttpContext.Request.Headers["Authorization"].Substring(7).Trim();
                string userId = CommonToken.DecodeToken(token, false).UserID;

                input.CreateId = userId;
                input.CreateTime = DateTime.Now;
                studentCashService.EditStudentCash(input);
            }
            catch (Exception ex)
            {
                resp.Code = 500;
                resp.Message = "操作失败" + ex.Message;
            }
            return JsonHelper.Serialize(resp);
        }

        [LoginFilter]
        [HttpPost]
        [Route("deleteStudentCash")]
        public string DeleteStudentCash(string id)
        {
            MyResponse resp = new MyResponse();
            try
            {
                studentCashService.DeleteStudentCash(id);
            }
            catch (Exception ex)
            {
                resp.Code = 500;
                resp.Message = "操作失败" + ex.Message;
            }
            return JsonHelper.Serialize(resp);
        }

        [LoginFilter]
        [HttpPost]
        [Route("deleteStudentCashBatch")]
        public string DeleteStudentCashBatch(List<string> ids)
        {
            MyResponse resp = new MyResponse();
            try
            {
                studentCashService.DeleteStudentCashBatch(ids);
            }
            catch (Exception ex)
            {
                resp.Code = 500;
                resp.Message = "操作失败" + ex.Message;
            }
            return JsonHelper.Serialize(resp);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="startTime">2018-02</param>
        /// <param name="endTime">2018-02</param>
        /// <returns></returns>
        [HttpGet]
        [Route("downLoadFile")]
        public FileResult DownLoadFile(string startTime ,string endTime)
        {
            List<CashExcelDto> list = studentCashService.GetCashExcelDto(startTime, endTime);
            ExcelBaseResult<CashExcelDto> excel = new Excel2003Result<CashExcelDto>(list, "", false, "");
            var fileStream = excel.GetExcelStream();
            return File(fileStream, "application/ms-excel", startTime +"至"+endTime+"奖学金统计报表.xls");
        }
    }
}